package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.search.mapper.SearchHistoryMapper;
import com.heima.search.service.SearchHistoryService;
import com.heima.model.search.pojo.SearchHistory;
import com.heima.model.search.dto.HistorySearchDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SearchHistoryServiceImpl extends ServiceImpl<SearchHistoryMapper, SearchHistory> implements SearchHistoryService {

    @Resource
    private SearchHistoryMapper searchHistoryMapper;

    @Override
    public void insert(String keyword, Long userId) {
        // 先检查是否已存在相同的搜索记录
        QueryWrapper<SearchHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("keyword", keyword);
        queryWrapper.eq("user_id", userId);

        SearchHistory existingHistory = searchHistoryMapper.selectOne(queryWrapper);

        if (existingHistory != null) {
            // 如果已存在，则更新搜索时间
            existingHistory.setCreatedTime(new Date());
            searchHistoryMapper.updateById(existingHistory);
            log.info("更新搜索历史成功，用户ID: {}, 关键词: {}", userId, keyword);
        } else {
            // 如果不存在，则新增记录
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setKeyword(keyword);
            searchHistory.setUserId(userId);
            searchHistory.setCreatedTime(new Date());

            searchHistoryMapper.insert(searchHistory);
            log.info("保存搜索历史成功，用户ID: {}, 关键词: {}", userId, keyword);
        }
    }

    @Override
    public List<SearchHistory> findUserSearchHistory(Long userId) {
        return searchHistoryMapper.selectByUserIdOrderByCreatedTimeDesc(userId);
    }

    @Override
    public void deleteUserSearchHistory(Long userId, HistorySearchDto dto) {
        if (dto.getId() != null) {
            searchHistoryMapper.deleteByUserIdAndId(userId, Long.valueOf(dto.getId()));
            log.info("删除搜索历史成功，用户ID: {}, 记录ID: {}", userId, dto.getId());
        }
    }
}
